package com.atguigu.chapter11;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/24 8:57
 */
public class Flink02_Table_BaseUse_Agg {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("sensor_1", 1L, 10),
            new WaterSensor("sensor_1", 2L, 20),
            new WaterSensor("sensor_2", 3L, 30),
            new WaterSensor("sensor_1", 4L, 40),
            new WaterSensor("sensor_1", 5L, 50)
        );
        
        // 1. 创建 table的执行环境
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        
        // 2. 把流转成一个动态表
        Table table = tenv.fromDataStream(stream);
        
        // select id, sum(vc) from t group by id;
        /*Table t1 = table
            .groupBy($("id"))
            .aggregate($("vc").sum().as("vc_sum"))
            .select($("id"), $("vc_sum"));*/
    
        Table t1 = table
            .groupBy($("id"))
            .select($("id"), $("vc").sum().as("vc_sum"));
        
    
        /*DataStream<Tuple2<Boolean, Row>> ds = tenv.toRetractStream(t1, Row.class);
        ds
            .filter(t -> t.f0)
            .map(t->t.f1)
            .print();*/
        t1.execute().print();
        
        env.execute();
        
    }
}
